package com.lzxzjy.web.servlet;

import com.alibaba.fastjson.JSON;
import com.lzxzjy.pojo.Book;
import com.lzxzjy.pojo.PageBean;
import com.lzxzjy.serivce.BookService;
import com.lzxzjy.serivce.impl.BookServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;

@WebServlet("/book/*")
public class BookServlet extends BaseServlet {
    private final BookService bookService = new BookServiceImpl();

    /**
     * 获取书籍状态
     * @param bookStateValue
     * @return
     */
    private int getBookState(String bookStateValue) {
        if ("true".equals(bookStateValue)) {
            return 11;
        } else if("false".equals(bookStateValue)){
            return -11;
        }
        return 0;
    }

    /**
     * 添加书籍，将前端的 JSON 字符串转成 Book 对象，通过调用 BookService 的方法写入数据库
     */
    public void insertBook(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 测试用
        // String test = request.getParameter("test");
        // Book book = JSON.parseObject(test, Book.class);

        // 接收数据
        BufferedReader bookReader = request.getReader();
        String bookLine = bookReader.readLine();

        // 处理数据
        Book book = JSON.parseObject(bookLine, Book.class);
        book.setBookLocation(toStringBookLocation(bookLine));
        book.setBookState(11);

        // 判断 Book 的值是否为空
        if (book.isEmpty()) {
            response.getWriter().write("empty");
            return;
        }

        // 调用方法将数据写入数据库
        boolean isSuccess = bookService.insertBook(book);

        // 响应写入成功的标识
        if (isSuccess) {
            response.getWriter().write("success");
        } else {
            response.getWriter().write("failure");
        }
    }

    /**
     * 将传入的书籍列表转为书籍Id号数组
     *
     * @param bookLine
     * @return
     */
    private int[] toIntArrayBookIds(String bookLine) {
        Book[] books = JSON.parseObject(bookLine, Book[].class);
        StringBuilder stringIds = new StringBuilder("[");
        for (Book book : books) {
            stringIds.append(book.getBookId());
            stringIds.append(",");
        }
        stringIds.replace(stringIds.length() - 1, stringIds.length(), "]");
        return JSON.parseObject(String.valueOf(stringIds), int[].class);
    }

    /**
     * 批量删除书籍
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void deleteBookByIds(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        BufferedReader bookReader = request.getReader();
        String bookLine = bookReader.readLine();

        // 处理数据
        if ("[]".equals(bookLine)) {
            return;
        }
        int[] bookIds = toIntArrayBookIds(bookLine);
        boolean isSuccess = bookService.deleteBookByIds(bookIds);
        if (isSuccess) {
            response.getWriter().write("success");
        } else {
            response.getWriter().write("failure");
        }
    }

    /**
     * 删除书籍
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void deleteBookById(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int bookId = Integer.parseInt(request.getParameter("bookId"));
        boolean isSuccess = bookService.deleteBookById(bookId);
        if (isSuccess) {
            response.getWriter().write("success");
        } else {
            response.getWriter().write("failure");
        }
    }

    /**
     * 修改书籍
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void updateBookById(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        BufferedReader bookReader = request.getReader();
        String bookLine = bookReader.readLine();
        String bookStateValue = request.getParameter("bookStateValue");
        Book book = JSON.parseObject(bookLine, Book.class);
        book.setBookLocation(toStringBookLocation(bookLine));
        if (getBookState(bookStateValue) != 0) {
            book.setBookState(getBookState(bookStateValue));
        }
        boolean isSuccess = bookService.updateBookById(book);
        if (isSuccess) {
            response.getWriter().write("success");
        } else {
            response.getWriter().write("failure");
        }
    }

    /**
     * 查询所有书籍，将查询到的数据转成 JSON 字符串发送到前端
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void selectAllBook(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 调用方法查询
        List<Book> books = bookService.selectAllBook();

        // 转化为 JSON 数据
        String jsonString = JSON.toJSONString(books);

        // 指明数据类型及字符集
        response.setContentType("text/json;charset=utf-8");
        // 写数据
        response.getWriter().write(jsonString);
    }

    /**
     * 分页查询书籍
     *
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void selectBookByPage(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 接收数据
        String _currentPage = request.getParameter("currentPage");
        String _pageSize = request.getParameter("pageSize");

        // 转换类型
        int currentPage = Integer.parseInt(_currentPage);
        int pageSize = Integer.parseInt(_pageSize);

        // 查询
        PageBean<Book> bookPageBean = bookService.selectBookByPage(currentPage, pageSize);

        // 转为 JSON 字符串
        String toJSONString = JSON.toJSONString(bookPageBean);

        // 写数据
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(toJSONString);
    }

    /**
     * 将传入的书籍位置数组转为字符串
     *
     * @param bookLine
     * @return
     */
    private String toStringBookLocation(String bookLine) {
        int index = bookLine.indexOf("\"bookLocationArray\":");
        int begin = bookLine.indexOf('[', index);
        int end = bookLine.indexOf("]", begin);
        return ((bookLine.substring(begin + 1, end).replace("\"", "")).replace(",", ""));
    }

    /**
     * 分页条件查询书籍
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void selectBookByPageAndTerms(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 接收数据
        BufferedReader bookReader = request.getReader();
        String bookLine = bookReader.readLine();

        String _currentPage = request.getParameter("currentPage");
        String _pageSize = request.getParameter("pageSize");

        // 处理数据
        Book book = JSON.parseObject(bookLine, Book.class);
        book.setBookAuthor('%' + book.getBookAuthor() + '%');
        book.setISBN('%' + book.getISBN() + '%');
        book.setBookName('%' + book.getBookName() + '%');
        book.setBookPublish('%' + book.getBookPublish() + '%');
        book.setBookType('%' + book.getBookType() + '%');
        book.setBookLocation("%" + toStringBookLocation(bookLine) + "%");

        int currentPage = Integer.parseInt(_currentPage);
        int pageSize = Integer.parseInt(_pageSize);

        // 查询
        PageBean<Book> bookPageBean = bookService.selectBookByPageAndTerms(book, currentPage, pageSize);

        // 转为 JSON 字符串
        String bookPageBeanLine = JSON.toJSONString(bookPageBean);

        // 写数据
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(bookPageBeanLine);
    }

    /**
     * 查询所有书籍所有的类型
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void selectAllBookType(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        List<String> bookType = bookService.selectAllBookType();
        String toJSONString = JSON.toJSONString(bookType);
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(toJSONString);
    }

}
